<template>
    <el-dialog v-model="dialogVisible" modal-class="reset" :before-close="handleClose" width="760px">
        <template #title>
            <div class="fs-16 bold">
                配置企业
            </div>
        </template>
        <div class="container">
            <div class="flex">
                <div class="flex-1">
                    <el-input v-model="searchValue" @input="handleInput" clearable class="w-50 m-2" placeholder="搜索"
                        suffix-icon="Search" />
                    <div>
                        <div class="flex flex-ai-c mg-t-12 border fc-black">
                            <div class="flex-1 bold flex flex-ai-c">
                                <el-checkbox v-model="isCheckAll" size="small" @change="handleAllChange"></el-checkbox>
                                <span class="mg-l-5">企业名称</span>
                            </div>
                            <div class="w-100 bold">
                                负责人
                            </div>
                        </div>
                        <el-scrollbar class="scroll-box">
                            <!-- <div class="scroll-box" @scroll="handleScroll($event)"> -->
                                <div class="flex flex-ai-c" v-for="(i, index) in companys" :key="index">
                                    <div class="flex-1">
                                        <el-checkbox v-model="i.selected" size="small"
                                            @change="handleCheckboxChange($event, i)">
                                            <!-- <el-tooltip class="box-item" effect="dark" :content="isBeyond('content', index) ? '' : i.companyName"
                                        placement="top-start" :disabled="isBeyond('content', index)">
                                        <div :ref="`content${index}`" class="single-line set-w-1"> {{ isBeyond('content', index) }}{{ i.companyName }} </div>
                                    </el-tooltip> -->
                                            <!-- <div :ref="`content${index}`" :title="isBeyond('content', index) ? '' : '111'" class="single-line set-w-1">{{ isBeyond('content', index) }}{{ i.companyName }}</div> -->
                                            <div v-isOver="i.serveCompanyName" class="single-line set-w-1">{{
                                                i.serveCompanyName
                                            }}
                                            </div>

                                        </el-checkbox>
                                    </div>
                                    <div class="w-100">
                                        {{ i.contacts }}
                                    </div>
                                </div>
                            <!-- </div> -->
                        </el-scrollbar>

                    </div>
                    <div class="flex mg-t-16">
                        <el-button type="primary" size="small" @click="handleSave">保存</el-button>
                        <el-button type="primary" plain size="small" @click="dialogVisible = false">取消</el-button>
                    </div>
                </div>
                <div class="flex-1 bg-gray">
                    <div class="title bold fs-16 shadow fc-black">
                        已选择{{ selectedCompanys.length }}个
                        <span v-if="errorList.length" class="fc-red fs-14">有{{ errorList.length }}家企业负责人出错，请重新选择</span>
                    </div>
                    <el-scrollbar class="scroll-box-2 set-pd">

                    <!-- <div class="scroll-box set-pd"> -->
                        <div class="flex flex-jc-sb flex-ai-start mg-t-10" v-for="(i, index) in selectedCompanys"
                            :key="index">
                            <div class="flex flex-1 flex-jc-sb mg-r-10">
                                <!-- <el-tooltip class="box-item" effect="dark" :content="i.serveCompanyName"
                                    placement="top-start" :disabled="isBeyond('content-', index)">
                                    <div class="single-line set-w-1">{{ i.serveCompanyName }}</div>
                                </el-tooltip> -->
                                <div v-isOver="i.serveCompanyName" class="single-line set-w-1">{{ i.serveCompanyName
                                }}
                                </div>
                            </div>
                            <div v-if="!i.isError" :ref="`content-${index}`">{{ i.contacts }}</div>
                            <div v-else class="set-margin">
                                <el-select v-model="i.contactsId" size="small" filterable remote reserve-keyword
                                    value-key="contactsId" placeholder="请输入姓名"
                                    :remote-method="(ev: any) => remoteMethod(ev, i)" @focus="getEmployeeList('', i)"
                                    @change="handleChange($event, i)">
                                    <el-option v-for="item in i.options" :key="item.contactsId" :label="item.contacts"
                                        :value="item.contactsId" />
                                </el-select>
                                <div v-if="i.showHint" class="fc-red fs-12 mg-t-5">请重新选择负责人</div>
                            </div>
                            <el-icon class="pointer mg-t-3 mg-l-10" @click="handleRemove(i)">
                                <CircleCloseFilled />
                            </el-icon>
                        </div>
                    <!-- </div> -->
                    </el-scrollbar>
                </div>
            </div>
        </div>
    </el-dialog>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import { ElMessage } from 'element-plus';

import { queryServeCompany, configAdvanceServeCompany, getEmployeeList, editServerCompany } from '@/api/advance';
import { cloneDeep, unionBy } from 'lodash';
export default defineComponent({
    props: {
        show: {
            type: Boolean,
            default: false
        },
        companyList: {
            type: Array,
            default() {
                return []
            }
        }
    },
    data() {
        return {
            dialogVisible: false,
            searchValue: '',
            // 公司列表
            companys: [] as any,
            // 已选择的公司
            selectedCompanys: [] as any,
            timer: null as any,
            errorList: [] as any,
            pageInfo: {
                pageNum: 1,
                pageSize: 300,
                total: 0
            },
            /**
             * 临时列表  所有的操作都基础临时列表
             * 包括分页时缓存操作过的数据  输入名称筛选时记录勾选的结果  删除时同时清空已选择列表和公司列表的选择状态
             * */
            tempList: [] as any,
            isCheckAll: false
        }
    },
    computed: {
        // isBeyond() {
        //     return (elName: string, index: number) => {
        //         // this.$nextTick(()=> {
        //             if (this.$refs[elName + index]) {
        //                 const el = this.$refs[elName + index] as any
        //                 console.log(777, el.clientWidth, el.scrollWidth);
        //                 return el.clientWidth >= el.scrollWidth
        //             }
        //         // })
        //     }
        // },
    },
    watch: {
        show(newval) {
            this.dialogVisible = newval
            if (newval) {
                this.getCompanyList()
            } else {
                this.tempList = (this as any).companyList
                this.errorList = []
            }
        },
        dialogVisible(newval) {
            this.$emit('update:show', newval)
        },
        companyList: {
            handler(newval) {
                this.tempList = cloneDeep(newval)
            },
        },
        tempList: {
            handler(newval) {
                this.selectedCompanys = newval
            },
            immediate: true
        }
    },
    methods: {
        handleInput() {
            if (this.timer) clearTimeout(this.timer)
            this.timer = setTimeout(() => {
                this.pageInfo.pageNum = 1
                this.getCompanyList()
            }, 300)
        },
        getCompanyList() {
            queryServeCompany({
                serveCompanyName: this.searchValue,
                pageNum: this.pageInfo.pageNum,
                pageSize: this.pageInfo.pageSize
            }, {
                loading: true
            }).then((res: any) => {
                this.pageInfo.total = res.totalCount
                if (this.pageInfo.pageNum === 1) {
                    this.companys = res.list
                } else {
                    this.companys = this.companys.concat(res.list)
                }
                this.companys.forEach((i: any) => {
                    if (!i.hasOwnProperty('selected')) {
                        i.selected = false
                    }
                    // 根据临时列表判断已选择了哪些并勾上
                    if (this.tempList?.length) {
                        i.selected = !!(this.tempList.find((k: any) => k.id === i.id))
                    }
                })
                this.isCheckAll = this.companys.every((i: any) => i.selected)
                console.log(12345, this.isCheckAll);
            })
        },
        // 保存配置企业
        handleSave() {
            configAdvanceServeCompany(this.selectedCompanys).then((res: any) => {
                if (res === true) {
                    ElMessage.success('保存成功')
                    this.$emit('success')
                    this.dialogVisible = false
                } else {
                    if (res?.length) {
                        this.errorList = res
                        res.forEach((i: any) => {
                            const exit = this.selectedCompanys.find((k: any) => k.id === i.id)
                            exit.isError = true
                            exit.showHint = true
                            exit.options = [
                                {
                                    contacts: exit.contacts,
                                    contactsId: exit.contactsId
                                }
                            ]
                        })
                    }
                }
            })
        },
        isBeyond(elName: string, index: number) {
            if (this.$refs[elName + index]) {
                const el = this.$refs[elName + index] as any
                return el.clientWidth >= el.scrollWidth
            }
            return false
        },
        handleClose() {
            this.dialogVisible = false
        },
        handleRemove(item: any) {
            item.selected = false
            // 删除时 删除临时列表的数据
            const index = this.tempList.findIndex((k: any) => k.id === item.id)
            if (index !== -1) {
                this.tempList.splice(index, 1)
            }
            // 公司列表对应的selected改成false
            const sltItem = this.companys.find(((i: any) => i.id === item.id)) as any;
            if (sltItem) {
                sltItem.selected = false
            }
        },
        remoteMethod(val: any, item: any) {
            if (this.timer) clearTimeout(this.timer)
            this.timer = setTimeout(() => {
                this.getEmployeeList(val, item)
            }, 300)
        },
        getEmployeeList(val: string, item: any) {
            getEmployeeList({
                userName: val
            }).then((res: any) => {
                if (res?.length) {
                    res.forEach((i: any) => {
                        i.contacts = i.userName
                        i.contactsId = i.userId
                    })
                    item.options = res
                }
            })
        },
        handleChange(ev: any, item: any) {
            const cur = item.options.find((i: any) => i.contactsId === ev)
            item.contacts = cur.contacts
            editServerCompany(item).then(res => {
                if (res) {
                    item.showHint = false
                    const index = this.errorList.findIndex((i: any) => i.id === item.id)
                    if (index !== -1) {
                        this.errorList.splice(index, 1)
                    }
                }
            })
        },
        handleScroll(ev: any) {
            const el = ev.target
            if (el.clientHeight + el.scrollTop >= el.scrollHeight && (this.pageInfo.pageNum * this.pageInfo.pageSize < this.pageInfo.total)) {
                this.pageInfo.pageNum++
                this.getCompanyList()
            }
        },
        handleCheckboxChange(ev: any, item: any) {
            const index = this.tempList.findIndex((i: any) => i.id === item.id)
            if (ev) {
                if (index === -1) {
                    this.tempList.push(item)
                }
            } else {
                if (index !== -1) {
                    this.tempList.splice(index, 1)
                }
            }
            console.log(22222, this.tempList);
        },
        handleAllChange() {
            this.companys.forEach((i: any) => i.selected = this.isCheckAll)
            if (this.isCheckAll) {
                this.tempList = cloneDeep(this.companys)
            } else {
                this.tempList = []
            }
        }
    },
    directives: {
        isOver: {
            mounted(el, bonding) {
                // console.log(el);
                // console.log(1111, el.clientWidth, el.scrollWidth);
                setTimeout(() => {
                    if (el.clientWidth < el.scrollWidth) {
                        el.title = bonding.value
                    }
                }, 0);
            }
        }
    }
})
</script>
<style lang="stylus" scoped>
.container
    margin-top -20px
.bg-gray
    background #FBFBFD
    border-radius 5px
    margin-left 16px
    // padding 16px
.title
    // border-bottom 1px solid #E8E9EA
    padding-bottom 18px
    padding 10px
.single-line
    white-space nowrap
    overflow hidden
    text-overflow ellipsis
.set-w-1
    width 200px
.set-margin
    margin-top -8px
.mg-t-3
    margin-top 3px
.scroll-box
    height 300px
    overflow auto
.scroll-box-2
    height 350px
    overflow auto
.border
    border-bottom 1px solid #E8E9EA
.shadow
    box-shadow 0 5px 10px -5px rgba(0,0,0,0.1)
.set-pd
    padding: 0 10px
.fc-black
    color #202536
</style>
<style>
.reset .el-dialog {
    border-radius: 12px !important;
}
.reset .el-icon-close {
    font-size: 20px;
    font-weight: bold;
}
</style>